import React from 'react';
import { Spin } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import { WeaErrorPage, WeaTools, WeaLocaleProvider, WeaTable } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
import Title from './Title';
import { setContentviewHeight } from '../../util/common';
import './index.less';

// 内容组件
class EContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabdata: props.edata.data,
      // currentTab: props.edata.currenttab,
      refresh: false,
      loadingCompleted: false,
      loading: false
    };
    this.query = {};// 点击more需要的参数

    if (window.element_news_refresh && typeof window == 'object') {
      window.element_news_refresh[props.config.params.eid] = this.refreshTabData;
    } else {
      let obj = {};
      obj[props.config.params.eid] = this.refreshTabData;
      window.element_news_refresh = obj;
    }
  }

  componentWillReceiveProps (nextProps) {
    if (!isEqual(nextProps, this.props)) {
      this.setState({
        tabdata: nextProps.edata.data,
        // currentTab: nextProps.edata.currenttab,
        refresh: false,
      });
    }
  }

  shouldComponentUpdate (nextProps, nextState) {
    return !isEqual(this.state, nextState) || !isEqual(this.props, nextProps);
  }

  componentWillMount () {
    const init = () => {
      this.setState({ loadingCompleted: true });
    };
    if (!window.weaOdoc) {
      window.eventRegister && window.eventRegister.loadModule('f_odoc', () => {
        console.log('加载成功');
        init();
      },
        console.log('加载失败'),
      );
    }
  }

  componentDidMount () {
    window.isOdocOpenWF = true;
    window.getOdocWFList = () => {
      setTimeout(() => {
        this.refreshTabData()
      }, 3000);
    };
    this.props.onRef(this);
  }
  componentWillUnmount () {
    window.isOdocOpenWF = null;
    window.getOdocWFList = null;
  }

  toggleTabPage = (tabid) => {
    const { handleTabData } = this.props;
    // const { currentTab } = this.state;
    this.setState({
      refresh: !(tabid === this.props.edata.currenttab),
    });
    handleTabData(tabid, true);
    this.handleTabData(tabid);
  }

  refreshTabData = () => {
    // const { currentTab } = this.state;
    this.setState({
      refresh: true,
    });
    this.handleTabData(this.props.edata.currenttab);
  }

  handleTabData = (tabid) => {
    const { changeMore } = this.props;
    const { params, isremembertab } = this.props.config;
    const tabdata_local = ls.getJSONObj(`tabdata-${params.eid}-${tabid}`);
    this.setState({
      // currentTab: tabid,
      tabdata: tabdata_local == null ? {} : tabdata_local,
      loading: true
    });

    WeaTools.callApi('/api/portal/element/odoccentertab', 'POST', { ...params, tabid }).then((result) => {
      this.setState({ loading: false })
      if (result.moreData) {
        const { showMore, moreUrl } = result.moreData;
        changeMore && changeMore(showMore, moreUrl);
      }
      ls.set(`tabdata-${params.eid}-${tabid}`, result);
      if (tabid === this.props.edata.currenttab) {
        this.setState({
          tabdata: result,
          refresh: false,
        });
        if (isremembertab) {
          let edata = ls.getJSONObj(`edata-${params.eid}`);
          if (edata) {
            edata.currenttab = tabid;
            edata.data = result;
            ls.set(`edata-${params.eid}`, edata);
          }
        }
      }
    });
  }

  render () {
    const { config, edata, handleRefresh, handleDelete, fontSizeMp, needMore, customClickMore } = this.props;
    const { tabdata, refresh, loadingCompleted, loading } = this.state;
    const { tabids = [], titles = [], esetting = {}, counts } = edata;
    const { tabsetting = {} } = tabdata;
    const { eid } = config.params;
    let { fontStyle, header } = config.item;
    const { contentview = {} } = config.item;
    if (!isEmpty(fontSizeMp)) fontStyle = fontSizeMp;
    esetting.fontStyle = fontStyle;
    let cstyle = {};
    if (header.displayPosition && header.displayPosition == 'bottom' && tabids && tabids.length > 1) {
      if (contentview.style.height) {
        if (esetting.tabstyle == '1' && esetting.tabvalue) {
          cstyle = setContentviewHeight(contentview.style.height, esetting.tabvalue);
        } else {
          cstyle = { height: `${parseInt(contentview.style.height) - 32}px`, overflow: 'auto' };
        }
      } else {
        cstyle = { height: contentview.style.height, overflow: 'auto' };
      }
    } else if (tabids && tabids.length == 1) {
      cstyle = { height: contentview.style.height, overflow: 'auto' };
    }
    if (header.displayPosition && header.displayPosition == 'bottom') {
      if (tabids && tabids.length > 1 || tabids && tabids.length == 1 && esetting.isAlwaysShow == '1') {
        let elementH = parseInt(contentview.style.height) - parseInt($(`#titleContainer_${eid}`).css('height')) - 33;
        if (elementH != parseInt(cstyle.height)) {
          if (elementH < parseInt(cstyle.height)) {
            cstyle.height = elementH + "px";
          }
        }
      }
    }
    let contentHtml = <div className="loading"> <Spin /> </div>;
    let more = '';
    let tabdata_img = {};
    if (!isEmpty(tabdata)) {
      tabdata_img = _.cloneDeep(tabdata);
      tabdata_img.tabsetting.imgs = [];
    }
    if (tabdata && tabdata.data && !loading) {
      more = tabsetting.more;
      if (tabsetting.showType == '0') {
        const list = tabdata.data.map(item => ({ key: 'index', ...item }));
        // esetting.showHeader = 1
        const tableType = tabsetting.tableType;
        const fontSize = `${fontSizeMp.contentfontsize}px`;
        contentHtml = (
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@tzvs2l`}
            columns={this.getColumn(tabdata.column, tableType, fontSize)}
            showHeader={esetting.showHeader == '1' && tableType == '0'}
            pagination={false}
            dataSource={list}
          />
        );
      } else if (loadingCompleted || (window.weaOdoc && window.weaOdoc.components)) {
        const PortalElement = window.weaOdoc.components.OdocPortalElement;
        contentHtml = <PortalElement ecId={`${this && this.props && this.props.ecId || ''}_PortalElement@lhrfeb`} showType={tabsetting.showType} datas={tabdata.data} />;
      }
    }

    const _titleProps = {
      currentTab: this.props.edata.currenttab,
      config,
      titles,
      tabids,
      handleRefresh,
      handleDelete,
      more,
      counts,
      isShowSettingShowType: tabsetting.isShowSettingShowType,
      fontSizeMp,
      tabwidth: esetting.tabwidth,
      methodvalue: esetting.methodvalue,
      tabstyle: esetting.tabstyle,
      tabvalue: esetting.tabvalue,
      handleTabData: this.toggleTabPage,
      needMore,
      customClickMore,
    };
    return (
      <div className="odoc-odocCenterPortal">
        <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@5lwx5c`} {..._titleProps} />
        <div className="tabContant" id={`tabcontant_${eid}`} style={{ height: cstyle.height, 'overflow-y': 'auto' }}>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@d1b0pg`} spinning={refresh}>{contentHtml}</Spin>
        </div>
      </div>
    );
  }

  getColumn (column = [], tableType, fontSize) {
    let columns = [];
    const width = `${100 / column.length}%`;
    const specialField = ['requestname', 'doctitle'];
    // 单行列表
    if (tableType == '0') {
      column.forEach((item) => {
        columns.push({
          title: <span className='font'>{item.value}</span>,
          dataIndex: item.key,
          key: item.key,
          width: item.width == '*' ? 'auto' : item.width,
          render: (fieldObj, record) => {
            const style = {
              width: item.width == '*' ? 'auto' : item.width
            }
            if (specialField.includes(item.key)) {
              // 公文流程 无字段
              if (fieldObj.link === '') {
                return <span style={style}>-</span>;
              }
              return (
                <a onClick={() => window.open(fieldObj.link)} style={{ fontSize, ...style }} className="textOverflow font" title={this.getHtmlWord(fieldObj.name)}>
                  <span dangerouslySetInnerHTML={{ __html: fieldObj.name }}></span>
                  {record[item.key] && record[item.key].read === 'false' && <span style={{ display: 'inline-block', height: '5px', width: '5px', background: 'red', borderRadius: '5px' }} />}
                </a>
              );
            } else if (item.key == 'creater') {
              return <a href={`javaScript:openhrm(${record.creater.id})`} className="textOverflow font" onClick={pointerXY} style={style} >{record.creater.name}</a>;
            } else if (item.key == 'doclink') {
              return <span
                title={record.doclink.name}
                className='textOverflow font'
                style={{
                  background: record.doclink.background,
                  color: record.doclink.color,
                  padding: '4px 6px',
                  maxWidth: '60px',
                  display: "inline-block",
                  width: 'auto',
                  ...style
                }}
              >{record.doclink.name}</span>;
            } else if (item.key == 'urgencydegree') {
              const styleNew = this.geturgencydegree(record);
              return <span title={record.urgencydegree.name} className="textOverflow font" style={{ ...style, ...styleNew, padding: '4px 6px', display: 'inline-block', maxWidth: '60px', width: 'auto' }}>{record.urgencydegree.name}</span>;
            }
            const showName = record[item.key] ? (record[item.key].name || record[item.key].name == '') ? record[item.key].name : record[item.key] : '-';
            return <span style={{ fontSize, ...style }} className="textOverflow font" title={showName}>{showName}</span>;
          },
        });
      });
      // 双行列表
    } else if (tableType == '1') {
      columns.push({
        title: 'aaa',
        dataIndex: 'aaa',
        key: 'aaa',
        render: (fieldObj, record) => this.getDoubelCol(record, fontSize),
      });
    } else if (tableType == '2') {
      columns.push({
        title: 'aaa',
        dataIndex: 'aaa',
        key: 'aaa',
        render: (fieldObj, record) => this.getDocThumbnail(record, fontSize),
      });
    }
    return columns;
  }

  getDoubelCol (record, fontSize) {
    return (
      <div className="doubelColContent font" style={{ fontSize }} key={record.key}>
        <div className="layoutLeft">
          {/* 无字段 */}
          {
            (
              (record.requestname && record.requestname.link === '') ||
              (record.doctitle && record.doctitle.link == '')
            ) &&
            <span>-</span>
          }
          {/* 公文流程 */}
          {
            record.requestname && record.requestname.link !== '' &&
            <a className="firstRow textOverflow"
              onClick={() => window.open(record.requestname.link)}
              title={this.getHtmlWord(record.requestname.name)}
            >
              <span dangerouslySetInnerHTML={{ __html: record.requestname.name }}></span>
              {record.requestname.read === 'false' && <span style={{ display: 'inline-block', height: '5px', width: '5px', background: 'red', borderRadius: '5px' }} />}
            </a>
          }
          {/* 公文库 */}
          {
            record.doctitle && (!record.requestname || record.requestname.name == '') &&
            <a className="firstRow textOverflow" onClick={() => window.open(record.doctitle.link)} title={record.doctitle.name}>
              {record.doctitle.name}
              {record.doctitle.read === 'false' && <span style={{ display: 'inline-block', height: '5px', width: '5px', background: 'red', borderRadius: '5px' }} />}
            </a>
          }

          <div className="secendRow">
            {
              Object.keys(record).map((key) => {
                if (key == 'requestname' || key == 'key' || key == 'doclink') {

                } else if (key == 'creater') {
                  return (
                    <div className="secendRow-item textOverflow" title={`${record[key].title}:${record[key].name}`}>
                      <span>{record[key].title}:</span>
                      <a className="mgl-10" href={`javaScript:openhrm(${record[key].id});`} onClick={pointerXY}>{record[key].name}</a>
                    </div>
                  );
                } else if (key == 'doctitle') {
                  return (
                    <div className="secendRow-item textOverflow" title={`${record[key].title}:${record[key].name}`}>
                      <span>{record[key].title}:</span>
                      <a className="mgl-10" onClick={() => window.open(record.doctitle.link)}>{record[key].name}</a>
                    </div>
                  );
                } else if (key == 'urgencydegree') {
                  const style = this.geturgencydegree(record);
                  return (
                    <div className="secendRow-item textOverflow" title={`${record[key].title}:${record[key].name}`}>
                      <span>{record[key].title}:</span>
                      <span className="mgl-10" className='textOverflow urgencydegree' style={{ ...style }}>{record[key].name}</span>
                    </div>
                  );
                } else {
                  return (
                    <div className="secendRow-item textOverflow" title={`${record[key].title}:${record[key].name}`}>
                      <span>{record[key].title}:</span>
                      <span className="mgl-10" dangerouslySetInnerHTML={{ __html: record[key].name }} />
                    </div>
                  );
                }
              })
            }
          </div>
        </div>
        <div className="layoutRight">
          {record.doclink && record.doclink.name &&
            <div
              className="doclink"
              style={{ color: record.doclink.color, background: record.doclink.background }}
              title={record.doclink.name}
            >{record.doclink.name}</div>}
        </div>
      </div>
    );
  }

  getDocThumbnail (record, fontSize) {
    const imgUrl = record.requestname && record.requestname.img != null ?
      record.requestname.img :
      record.doctitle && record.doctitle.img != null ? record.doctitle.img : '';
    return (
      <div className="odocThumnail font" style={{ fontSize }} key={record.key}>
        <div className="firstColumn">
          <img src={imgUrl} className="previewImg" />
        </div>
        <div className="secendColumn">
          {/* 无字段 */}
          {
            (
              (record.requestname && record.requestname.link === '') ||
              (record.doctitle && record.doctitle.link == '')
            ) &&
            <span>-</span>
          }
          {
            record.requestname &&
            <a className="firstRow textOverflow" onClick={() => window.open(record.requestname.link)} title={this.getHtmlWord(record.requestname.name)}>
              <span dangerouslySetInnerHTML={{ __html: record.requestname.name }}></span>
              {record.requestname && record.requestname.read === 'false' && <span style={{ display: 'inline-block', height: '5px', width: '5px', background: 'red', borderRadius: '5px' }} />}
            </a>
          }
          {
            record.doctitle && (!record.requestname || record.requestname.name == '') &&
            <a className="firstRow textOverflow " onClick={() => window.open(record.doctitle.link)} title={record.doctitle.name}>
              {record.doctitle.name}
              {record.doctitle.read === 'false' && <span style={{ display: 'inline-block', height: '5px', width: '5px', background: 'red', borderRadius: '5px' }} />}
            </a>
          }

          {
            Object.keys(record).map((key) => {
              if (key == 'requestname' || key == 'key' || key == 'doclink') {

              } else if (key == 'creater') {
                return (
                  <div className="listItem textOverflow" title={`${record[key].title}:${record[key].name}`}>
                    {record[key].title}:<a href={`javaScript:openhrm(${record[key].id});`} onClick={pointerXY} className="mgl-10">{record[key].name}</a>
                  </div>
                );
              } else if (key == 'urgencydegree') {
                const style = this.geturgencydegree(record);
                return (
                  <div className="listItem textOverflow " title={`${record[key].title}:${record[key].name}`}>
                    {record[key].title}:<span className="mgl-10 textOverflow urgencydegree" style={{ ...style }}>{record[key].name}</span>
                  </div>
                );
              } else if (key == 'doctitle') {
                return (
                  <div className="secendRow-item textOverflow" title={`${record[key].title}:${record[key].name}`}>
                    <span>{record[key].title}:</span>
                    <a className="mgl-10" onClick={() => window.open(record.doctitle.link)}>{record[key].name}</a>
                  </div>
                );
              } else {
                return (
                  <div className="listItem textOverflow" title={`${record[key].title}:${record[key].name}`}>
                    {record[key].title}:<span className="mgl-10">{record[key].name}</span>
                  </div>
                );
              }
            })
          }
        </div>
        <div className="thirdColumn">
          {record.doclink && record.doclink.name && <div className="doclink" style={{ color: record.doclink.color, background: record.doclink.background }} title={record.doclink.name}>{record.doclink.name}</div>}
        </div>
      </div>
    );
  }

  geturgencydegree (record) {
    const style = {};
    if (record.urgencydegree.style) {
      const str = record.urgencydegree.style.substr(1, record.urgencydegree.style.length - 2);
      str.split(',').forEach((item) => {
        const arr = item.split(':');
        style[arr[0]] = arr[1];
      });
    }
    return style;
  }

  getParams () {
    return this.query;
  }

  getHtmlWord = (word) => {
    if (typeof word != 'string') {
      return word
    }
    const stack = [];
    let resultStr = ''
    word.split('').forEach(str => {
      str == '<' && stack.push(str)
      stack.length == 0 && (resultStr += str)
      str == '>' && stack.pop()
    })
    if (stack.length > 0) {
      return word;
    }
    return resultStr
  }

}

class MyErrorHandler extends React.Component {
  render () {
    const hasErrorMsg = this.props.error && this.props.error !== '';
    return (<WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@3irxvg`} msg={hasErrorMsg ? this.props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />
    );
  }
}

EContent = WeaTools.tryCatch(React, MyErrorHandler, { error: '' })(EContent);
export default EContent;